package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.util.StringUtil;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.AlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserMapper;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 报警规则Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-04
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return save(alertRule) ? 1 : 0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return updateById(alertRule) ? 1 : 0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private AlertDataService alertDataService;
    @Autowired
    private WebSocketServer webSocketServer;
    @Override
    public void alertFilter() {
        // 查询所有规则
        List<AlertRule> alertRuleList = this.list(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        if (CollUtil.isEmpty(alertRuleList)) {
            return;
        }
        // 查询所有设备上报的数据
        List values = redisTemplate.opsForHash().values(Constants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(values)) {
            return;
        }
        // 解析上报数据
        List<DeviceData> deviceDataList = new ArrayList<>();
        values.forEach(value -> {
            List<DeviceData> list = JSONUtil.toList(value.toString(), DeviceData.class);
            deviceDataList.addAll(list);
        });
        // 数据报警处理器
        deviceDataList.forEach(deviceData -> {
            alertFilter(deviceData);
        });
    }

    private void alertFilter(DeviceData deviceData) {
        //1.判断当前上报的数据是否超过1分钟，只接收实时数据，过期数据都不在报警了
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 60) {
            return;
        }
        //2.查询该产品物模型下的全部设备的规则
        List<AlertRule> alertRuleList = this.list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
        );
        if (CollUtil.isEmpty(alertRuleList)) {
            return;
        }
        //3.遍历每一条规则，并进行校验
        alertRuleList.forEach(alertRule -> {
            deviceDataAlarmHandle(alertRule, deviceData);
        });
    }

    private void deviceDataAlarmHandle(AlertRule alertRule, DeviceData deviceData) {
        //1.判断是否在生效时间内
        String[] split = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        LocalTime alarmTime = deviceData.getAlarmTime().toLocalTime();
        if (alarmTime.isBefore(startTime) && alarmTime.isAfter(endTime)) {
            return;
        }
        //2.检验数据是否达到阈值
        String iotId = deviceData.getIotId();
        //设置报警数量的key
        String alertCountKey = Constants.ALERT_TRIGGER_COUNT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        Double dataValue = Double.valueOf(deviceData.getDataValue());
        String operator = alertRule.getOperator();
        Long value = alertRule.getValue();
        int compare = NumberUtil.compare(dataValue, value);
        if(operator.equals("<") && compare < 0 || operator.equals(">=") && compare >= 0){

        }else{
            redisTemplate.delete(alertCountKey);
            return;
        }
        //3.判断是否在沉默周期内
        String silentKey = Constants.ALERT_SILENT_PREFIX+iotId+":"+deviceData.getFunctionId()+":"+alertRule.getId();
        String silentTime = (String) redisTemplate.opsForValue().get(silentKey);
        if(StringUtil.isNotEmpty(silentTime)){
            return;
        }
        //4.判断持续周期
        String alertCount = (String) redisTemplate.opsForValue().get(alertCountKey);
        int count = StringUtil.isEmpty(alertCount) ? 1 : Integer.parseInt(alertCount) + 1;
        if(count != alertRule.getDuration()){
            redisTemplate.opsForValue().set(alertCountKey, String.valueOf(count));
            return;
        }
        //5.校验全部通过，则进行报警
        redisTemplate.delete(alertCountKey);
        redisTemplate.opsForValue().set(silentKey, String.valueOf(alertRule.getAlertSilentPeriod()));
        List<Long> userIds = new ArrayList<>();
        if(alertRule.getAlertDataType() == 0){
            if(deviceData.getLocationType() == 0){
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            }else if (deviceData.getLocationType() == 1 && deviceData.getPhysicalLocationType() == 2){
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
        }else {
            userIds = sysUserRoleMapper.selectUserIdByRoleName("维修工");
        }
        List<Long> superManager = sysUserRoleMapper.selectUserIdByRoleName("超级管理员");
        userIds.addAll(superManager);
        userIds =  userIds.stream().distinct().collect(Collectors.toList());
        //保存报警信息
        List<AlertData> alertDataList = insertAlertData(userIds,alertRule,deviceData);

        websocketNotity(alertDataList.get(0), alertRule,userIds);
    }
    private void websocketNotity(AlertData alertData, AlertRule rule, Collection<Long> allUserIds) {

        // 属性拷贝
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setFunctionName(rule.getFunctionName());
        alertNotifyVo.setAlertDataType(rule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);
        // 向指定的人推送消息
        webSocketServer.sendMessageToConsumer(alertNotifyVo, allUserIds);

    }

    private List<AlertData> insertAlertData(List<Long> userIds, AlertRule alertRule, DeviceData deviceData) {
        // 对象拷贝
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());
        // 心率<60,持续3个周期就报警
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        alertData.setAlertReason(alertReason);
        alertData.setStatus(0);
        alertData.setType(alertRule.getAlertDataType());
        // 遍历allUserIds
        List<AlertData> list = userIds.stream().map(userId -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(userId);
            dbAlertData.setId(null);
            return dbAlertData;
        }).collect(Collectors.toList());
        // 批量保存
        alertDataService.saveBatch(list);
        return list;
    }
}
